package com.toutiaohot.file.controller;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;


@Slf4j
@RestController
public class FileController {

    private static final String SEP_A = "(";
    private static final String SEP_B = ")";

    @Value("${file.upload.path:D://file}")
    private String outPath;

    @RequestMapping("/upload")
    public String upload(@RequestParam("files") MultipartFile[] files) {
        JSONObject jsonObject = new JSONObject();
        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getOriginalFilename();
            try{

            File dest = new File(outPath+"/"+fileName);
                if (dest.exists()){
                    dest = new File(outPath+"/"+fileRename(fileName));
                }
            if (!dest.getParentFile().exists()){
                boolean flag =  dest.getParentFile().mkdirs();
                if (!flag){
                    throw new Exception("文件目录创建失败");
                }
            }
                files[i].transferTo(dest);
            }catch (Exception e){
                log.error("上传文件异常",e);
                jsonObject.put("success","false");
                jsonObject.put("msg",e.getMessage());
                return jsonObject.toJSONString();
            }
        }
        jsonObject.put("success",true);
        jsonObject.put("msg","成功");
        return jsonObject.toJSONString();
    }



    private static String fileRename(String fullName){
        int index = fullName.lastIndexOf(".");
        if (index == -1||!(fullName.contains(SEP_A)&&fullName.contains(SEP_B))){
            return fullName;
        }else {
            //先截取前半部分
            String fileName = fullName.substring(0,index);
           int indexA = fileName.lastIndexOf(SEP_A);
           String tailName = fileName.substring(indexA,fileName.length());
           String aheadName = fileName.substring(0,indexA);
           try {
               int i = Integer.parseInt(tailName.substring(1,tailName.length()-1));
               i =i+1;
               tailName = SEP_A+i+SEP_B;
               return aheadName +tailName;
           }catch (Exception e){
               return fullName;
           }

        }

    }


    public static void main(String[] args) {
        log.info(fileRename("abc(100)"));
    }

    @GetMapping("/download")
    public String download(HttpServletResponse response,@RequestParam ("fileName") String fileName){
        File file = new File(outPath +"/"+fileName);
        JSONObject jsonObject = new JSONObject();
        if (!file.exists()){
            jsonObject.put("success",false);
            jsonObject.put("msg","文件不存在");
            return jsonObject.toJSONString();
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("UTF-8");
        response.setContentLength((int)file.length());
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));){
            byte[] buff = new byte[1024];
            OutputStream os = response.getOutputStream();
            int i= 0;
            while ((i = bis.read(buff) )!= -1){
                os.write(buff,0,i);
                os.flush();
            }
        } catch (FileNotFoundException e) {
            log.error("下载失败",e);
            jsonObject.put("success","false");
            jsonObject.put("msg",e.getMessage());
            return jsonObject.toJSONString();
        } catch (IOException e) {
            log.error("下载失败",e);
            jsonObject.put("success","false");
            jsonObject.put("msg",e.getMessage());
            return jsonObject.toJSONString();
        }

        jsonObject.put("success",true);
        jsonObject.put("msg","成功");
        return jsonObject.toJSONString();
    }

}
